package com.alm.token.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.BaseDialogBean;
import com.alm.token.ui.data.bean.LoginData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.fragmentDialog.CreatNodeDialogFragment;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.LoginView;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.SpUtil;
import com.alm.token.utils.Utils;
import com.cryptape.cita_wallet.activity.AddWalletActivity;
import com.cryptape.cita_wallet.activity.FingerPrintActivity;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;

import baibeiwallet.WalletManagerActivity1;
import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.Optional;

import static com.cryptape.cita_wallet.activity.SplashActivity.LOCK_TO_MAIN;

public class BlockWalletLoginActivity extends BaseActivity implements LoginView<LoginData>, RadioGroup.OnCheckedChangeListener {
//    @BindView(R.id.centerItem)
//    TextView centerItem;
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.leftItem)
    TextView leftItem;
    @BindView(R.id.find_pwd)
    TextView findPwd;
    @BindView(R.id.edt_inputusername)
    EditText edtUsername;
    @BindView(R.id.edt_inputpsw)
    EditText edtPsw;
    @BindView(R.id.gologin)
    TextView tvBtnLogin;
    @BindView(R.id.tv_rememberpsw)
    CheckBox tvBtnRememberpsw;
    @BindView(R.id.tv_changelanguage)
    LinearLayout tvChangelanguage;
    @BindView(R.id.img_chinalanguage)
    ImageView img_chinalanguage;
    @BindView(R.id.tv_langrage)
    TextView tv_langrage;
    @BindView(R.id.img_changeshow)
    ImageView img_changeshow;

    @BindView(R.id.tv_inputusernameshow)
    TextView tv_inputusernameshow;
    @BindView(R.id.tv_inputpswshow)
    TextView tv_inputpswshow;
    @BindView(R.id.radioButton_trawallet_item)
    RadioButton radioButtonTrawalletItem;
    @BindView(R.id.radioButton_nodewallet_item)
    RadioButton radioButtonNodewalletItem;
    @BindView(R.id.rg_wallet_select)
    RadioGroup rgWalletSelect;

    private boolean isRemberPsw = false;
    private boolean isPressed;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_block_wallet_login;
    }

    @Override
    protected void initVariables() {
        SpUtil.putString(MyApp.context, ConStant.TOKEN, "");
        SpUtil.putString(MyApp.context, ConStant.MEIQIAID, "");
        int flag = LanguageUtils.getSetIndex();
        img_chinalanguage.setImageDrawable(getResources().getDrawable(flag == 4 ? R.drawable.japanese : flag == 2 ? R.drawable.america
                : flag == 3 ? R.drawable.korea : R.drawable.china));
        tv_langrage.setText(flag == 4 ? "日本語" : flag == 2 ? "English"
                : flag == 3 ? "한국어" : "中文");
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (group.getCheckedRadioButtonId()) {
//            case R.id.radioButton_trawallet_item:
//                mainActySetWallet(0);
//                break;
            case R.id.radioButton_nodewallet_item:
                gotoMainPage();
                group.check(R.id.radioButton_trawallet_item);
//                mainActySetWallet(1);
                break;
        }
    }

    private void gotoMainPage() {
        if (!TextUtils.isEmpty(SharePrefUtil.getCurrentWalletName())) {
            if (SharePrefUtil.getBoolean(ConstantUtil.FINGERPRINT, false)) {
                Intent intent = new Intent(this, FingerPrintActivity.class);
                intent.putExtra(LOCK_TO_MAIN, true);
                startActivityForResult(intent,0);
            } else {
                startActivityForResult(new Intent(this, com.cryptape.cita_wallet.activity.MainActivity.class),1);
            }
        } else {
            Intent intent = new Intent(this, AddWalletActivity.class);
            startActivityForResult(intent,2);
        }
    }


    private void showCreatNodeDialog() {
        CreatNodeDialogFragment dialogFragment = new CreatNodeDialogFragment();
        UserWalletData.DataBean.UserMsgBean userMsgBean1 = new UserWalletData.DataBean.UserMsgBean();
        userMsgBean1.setTitle(getString(R.string.common_warmprompt));
        userMsgBean1.setEnTitle(getString(R.string.common_warmprompt));
        userMsgBean1.setContent(getString(R.string.wallet_hint_nowallet_worm));
        userMsgBean1.setEnContent(getString(R.string.wallet_hint_nowallet_worm));
        dialogFragment.setDialogBean(new BaseDialogBean(userMsgBean1));

        dialogFragment.setListener(new CreatNodeDialogFragment.ClickListener() {
            @Override
            public void Listener(String name, int potion) {
                if (potion == 2) {
                    Intent i = new Intent(BlockWalletLoginActivity.this, WalletManagerActivity1.class);
                    startActivity(i);

                } else {
                    //                    Intent i1 = new Intent(getActivity(), InprotWalletActivity1.class);
//                    startActivity(i1);
                }

            }
        });
        dialogFragment.show(getSupportFragmentManager(),"NoticeDialogFragment");
//        dialogFragment.show(getFragmentManager(), "NoticeDialogFragment");
        getSupportFragmentManager().executePendingTransactions();
    }

    @Override
    protected void initViews() {
        findPwd.setOnClickListener(this);
        rightItem.setOnClickListener(this);
        tvChangelanguage.setOnClickListener(this);
        leftItem.setOnClickListener(this);
        tvBtnLogin.setOnClickListener(this);
        img_changeshow.setOnClickListener(this);
        boolean s = MyApp.context != null;

        edtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_inputusernameshow.setVisibility(EmptyUtils.isNotEmpty(edtUsername.getText().toString()) ? View.VISIBLE : View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        edtPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_inputpswshow.setVisibility(EmptyUtils.isNotEmpty(edtPsw.getText().toString()) ? View.VISIBLE : View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        isRemberPsw = SpUtil.getBoolean(MyApp.context, ConStant.REMBERPSW, false);
        edtUsername.setText(SpUtil.getString(MyApp.context, ConStant.USERNAME, ""));

        if (isRemberPsw) {
            tvBtnRememberpsw.setButtonDrawable(R.drawable.check_box_select);
            edtPsw.setText(SpUtil.getString(MyApp.context, ConStant.PSW, ""));
        } else {
            tvBtnRememberpsw.setButtonDrawable(R.drawable.check_box);
        }
        rgWalletSelect.setTag(1);
        rgWalletSelect.setOnCheckedChangeListener(this);
    }

    @Override
    protected void loadData() {
//        mMyPresenter.getLoginData("test", "123456");
    }

    //Test @Optional
    @Optional
    @OnCheckedChanged(R.id.tv_rememberpsw)
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            tvBtnRememberpsw.setButtonDrawable(R.drawable.check_box_select);
        } else {
            tvBtnRememberpsw.setButtonDrawable(R.drawable.check_box);
        }
        SpUtil.putBoolean(MyApp.context, ConStant.REMBERPSW, isChecked);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_changelanguage:
            case R.id.leftItem:
                startActivityForResult(SetLanguageActivity.class,3);
                break;
            case R.id.rightItem:
                startActivity(BlockWalletRegisterActivity.class);
                break;
            case R.id.img_changeshow:
                isPressed = !isPressed;
                img_changeshow.setSelected(isPressed);

                if (img_changeshow.isSelected()) {
                    //选择状态 显示明文--设置为可见的密码
                    edtPsw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    edtPsw.setInputType(
                            InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                edtPsw.setSelection(edtPsw.getText().toString().length());
                break;
            case R.id.find_pwd:
                startActivity(FindPwdActivity.class);
                break;
            case R.id.gologin:
                if (edtPsw.getText().toString().isEmpty() || edtUsername.getText().toString().isEmpty()) {
                    showToast(getString(R.string.profile_hint_warn1));
                    break;
                }
                if (!Utils.verifyUserName(edtUsername.getText().toString())) {
                    showToast(getString(R.string.profile_hint_warn2));
                    break;
                }
                if (edtUsername.getText().toString().length() < 4 || edtUsername.getText().toString().length() > 18) {
                    showToast(getString(R.string.profile_hint_warn3));
                    break;
                }
                if (!Utils.verifyUserNameFL(edtUsername.getText().toString())) {//[A-Za-z1-9]{2}
                    showToast(getString(R.string.profile_hint_warn4));
                    break;
                }

//                if (!Utils.verifyUserName(edtPsw.getText().toString())) {
//                    showToast(getString(R.string.profile_hint_warn22));
//                    break;
//                }
                if (edtPsw.getText().toString().length() < 4 || edtPsw.getText().toString().length() > 20) {
                    showToast(getString(R.string.profile_hint_warn33));
                    break;
                }

//                if (!Utils.verifyUserNameFL(edtPsw.getText().toString())) {//[A-Za-z1-9]{2}
//                    showToast(getString(R.string.profile_hint_warn44));
//                    break;
//                }

                preenter.getLoginData(edtUsername.getText().toString(), edtPsw.getText().toString());
                break;
        }
    }

    @Override
    public void getData(LoginData loginData) {

        if (loginData.getStatus() == 0) {
//            showToast(loginData.getMsg());
            MyApp.userName = edtUsername.getText().toString();
            SpUtil.putString(MyApp.context, ConStant.TOKEN, loginData.getData());
            SpUtil.putString(MyApp.context, ConStant.MEIQIAID, loginData.getTotal());
            SpUtil.putString(MyApp.context, ConStant.USERNAME, edtUsername.getText().toString());
            SpUtil.putString(MyApp.context, ConStant.PSW, edtPsw.getText().toString());
            MyApp.setToken(loginData.getData());//获取到Token
            startActivity(MainActivity.class);
//          overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            finish();
        } else if (loginData.getStatus() == 3) {
            showToast(getString(R.string.profile_hint_warn));
        } else {
            showToast(loginData.getMsg() + ("Password error 密码错误 암호 오류".contains(loginData.getMsg()) ? getString(R.string.login_hint_warm3) : ""));
        }

    }

    @Override
    public void jumpToLoginAct(int staue) {

        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }

    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.profile_hint_warn5));
//        showToast(error);
    }

    @Override
    public void ShowProgress() {
        showWaitDialog(R.string.login_loading_hint);
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    Long mExitTime = 0L;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 3000) {
            Toast.makeText(BlockWalletLoginActivity.this, getString(R.string.profile_hint_item12) + getString(R.string.app_name), Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if(resultCode == Activity.RESULT_CANCELED)
//        rgWalletSelect.check(R.id.radioButton_trawallet_item);
//        radioButtonNodewalletItem.setChecked(true);
//        radioButtonTrawalletItem.setChecked(false);
    }
}
